package com.da.javatest.demo.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

import com.da.javatest.bean.Worker;

/**
 * @author chenlida
 * @date 2019/4/18 11:09
 * @description
 */
public class MapTest {
    public static void main(String[] args) {
        MapTest mapTest = new MapTest();
        Map<String, List<Worker>> map = mapTest.convert2MapList(mapTest.getWorkerList(), Worker::getName);
        map.values().forEach(System.out::println);

        String nameTemplate = "%s(%s)";
        System.out.println(String.format(nameTemplate, "陈立达", "达少"));

        Map<String, String> test = new HashMap<>();
        test.put("cc", "dd");
        System.out.println(Objects.isNull(test.get("aa")));

        List<String> list = Arrays.asList("aa", "bb", "cc");
        list.forEach(l -> {
            if (l.equals("bb")) {
                return;
            }
            System.out.println(l);
        });
    }

    private List<Worker> getWorkerList() {
        return Arrays.asList(new Worker(1, "aa", 11), new Worker(2, "aa", 22), new Worker(3, "bb", 33),
            new Worker(4, "cc", 44));
    }

    private <T> Map<String, List<T>> convert2MapList(List<T> list, Function<T, String> keyFunction) {
        Map<String, List<T>> recordDTOMap = new HashMap<>(list.size());
        list.forEach(recordDTO -> {
            String key = keyFunction.apply(recordDTO);
            if (recordDTOMap.containsKey(key)) {
                recordDTOMap.get(key).add(recordDTO);
            } else {
                List<T> recordList = new ArrayList<>();
                recordList.add(recordDTO);
                recordDTOMap.put(key, recordList);
            }
        });
        return recordDTOMap;
    }

    private <T> Map<String, T> convert2Map(List<T> list, Function<T, String> keyFunction) {
        Map<String, T> recordDTOMap = new HashMap<>(list.size());
        list.forEach(recordDTO -> {
            String key = keyFunction.apply(recordDTO);
            recordDTOMap.put(key, recordDTO);
        });
        return recordDTOMap;
    }

}


